/* Orbas:
 *     A open source CORBA Specification implementation from Huihoo.
 *
 * Copyright 2002-2003 Huihoo.org, Inc. All Right Reserved.
 *
 * This software is licensed under LGPL license.
 * See terms of license at gnu.org.
 *
 * For more information, visit:
 *
 * http://www.huihoo.org/orbas
 */

package org.huihoo.orbas.idl;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

class SwitchBody extends IdlSymbol {

	/** holds case list */
	Vector caseListVector = new Vector();

	TypeSpec ts = null;
	UnionType myUnion = null;

	public SwitchBody(int num) {
		super(num);
	}

	public void setTypeSpec(TypeSpec s) {
		ts = s;
		for (Enumeration e = caseListVector.elements(); e.hasMoreElements();) {
			Case c = (Case) e.nextElement();
			c.setPackage(pack_name);
			c.setTypeSpec(s);
		}
	}

	/**
	 * pass a reference to the containing union through to the case elements,
	 * which pass it on
	 */

	public void setUnion(UnionType ut) {
		myUnion = ut;
		for (Enumeration e = caseListVector.elements(); e.hasMoreElements();) {
			Case c = (Case) e.nextElement();
			c.setUnion(ut);
		}
	}

	public void setEnclosingSymbol(IdlSymbol s) {
		if (enclosing_symbol != null && enclosing_symbol != s)
			throw new RuntimeException(
					"Compiler Error: trying to reassign container for " + name);
		enclosing_symbol = s;
		for (Enumeration e = caseListVector.elements(); e.hasMoreElements();)
			((IdlSymbol) e.nextElement()).setEnclosingSymbol(s);
	}

	public void setPackage(String s) {
		s = parser.pack_replace(s);
		if (pack_name.length() > 0)
			pack_name = new String(s + "." + pack_name);
		else
			pack_name = s;

		if (ts != null)
			ts.setPackage(s);
	}

	/**
	 * do the parsing
	 */

	public void parse() {
		Hashtable usedLabelNames = new Hashtable();

		for (Enumeration e = caseListVector.elements(); e.hasMoreElements();) {
			Case theCase = (Case) e.nextElement();
			theCase.parse();

			// get all case labels and check for duplicates

			IdlSymbol[] labels = theCase.getLabels();

			for (int i = 0; i < labels.length; i++) {
				if (labels[i] != null) // null means default
				{
					IdlSymbol sym = (IdlSymbol) usedLabelNames.get(labels[i]
							.toString());

					if (sym != null) {
						parser.error("Duplicate case label <" + sym.toString()
								+ ">", sym.get_token());
					}

					usedLabelNames.put(labels[i].toString(), labels[i]);
				}
			}
		}
		usedLabelNames.clear();

		ts.parse();
		myUnion.addImportedName(ts.typeName());

	}

	public void print(java.io.PrintWriter ps) {
		for (Enumeration e = caseListVector.elements(); e.hasMoreElements();) {
			Case c = (Case) e.nextElement();
			c.print(ps);
		}
	}

}
